package com.example.backed.utils;

import com.example.backed.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
@RequiredArgsConstructor
public class JwtUtil {

    private final JwtConfig jwtConfig;

    private SecretKey getSigningKey() {
        byte[] keyBytes = jwtConfig.getSecret().getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 从令牌中提取用户ID
     * 注意：这个方法名保持不变是为了减少代码变更，但实际上提取的是用户ID
     */
    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    /**
     * 从令牌中提取用户ID
     */
    public String extractUserId(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        // 如果UserDetails是User类的实例，使用用户ID作为subject
        if (userDetails instanceof com.example.backed.entity.User) {
            com.example.backed.entity.User user = (com.example.backed.entity.User) userDetails;
            return createToken(claims, user.getId().toString());
        }
        // 否则使用用户名作为subject（兼容旧代码）
        return createToken(claims, userDetails.getUsername());
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + jwtConfig.getExpiration() * 1000))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        // 从令牌中提取subject（现在是用户ID）
        final String subject = extractUsername(token);
        
        // 如果UserDetails是User类的实例，验证用户ID
        if (userDetails instanceof com.example.backed.entity.User) {
            com.example.backed.entity.User user = (com.example.backed.entity.User) userDetails;
            return subject.equals(user.getId().toString()) && !isTokenExpired(token);
        } 
        
        // 否则验证用户名（兼容旧代码）
        return subject.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }
} 